<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
        <el-form-item label="库存单位" prop="storageId">
          <drug-storage-dept ref="storageIdDeptRef" :clearable="false"
                             :org-id="queryParams.orgId" :value-storage-id="queryParams.storageId"
                             class="import-maste"
                             @drugStorageChange="storageIdClick"/>
        </el-form-item>
<!--        <el-form-item label="药品名称" prop="drugName">-->
<!--          <el-input v-model="queryParams.drugName" clearable placeholder="请输入药品名称"-->
<!--                    @keyup.enter.native="handleQuery"/>-->
<!--        </el-form-item>-->
        <el-form-item label="药品名称" prop="itemInfo">
          <el-input
            v-model="queryParams.itemInfo"
            clearable
            placeholder="请输入药品名称、药编码、拼音码"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="选择方式" prop="selectType">
          <el-radio-group v-model="queryParams.selectType" @change="handleQuery">
            <el-radio-button label="所有" value=""/>
            <el-radio-button label="无限制" value="2"/>
            <el-radio-button label="低于下限" value="1"/>
            <el-radio-button label="高于上线" value="3"/>
          </el-radio-group>
        </el-form-item>
        <div class="mr20" style="float: right">
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
          <el-button style="float: right" type="danger" @click="deleteBatch">清空本页</el-button>
          <el-button style="float: right" type="success" @click="saveBatch">保存本页</el-button>
        </div>
      </el-form>
    </div>
    <el-table v-adaptive :border="true" :data="drugStockList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row>
      <el-table-column :align="'center'" fixed="left" header-align="center" label="序号" prop="rowIndex"
                       width="50">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" header-align="center" label="药品名称"
                       prop="drugName">
        <template #default="scope">
          <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" label="药品编码" prop="drugCode"
                       width="100px"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" label="生产商" prop="firmName"
                       width="240px"/>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="最小规格" prop="minSpec" width="100"/>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="最小单位" prop="minUnits" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"/>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="包装规格" prop="packageSpec"
                       width="180px">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.packageSpec }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum" width="70"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="库存量" prop="minUnits"
                       width="160px">
        <template #default="scope">
          <template v-if="scope.row.quantityMin > 0">
            <!--小包装-->
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">
              {{ scope.row.quantityMin }}
            </div>
          </template>
          <!--大包装-->
          <template v-if="scope.row.quantityMax > 0">
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">{{ scope.row.quantityMax }}
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="上限" prop="actualQuantity" width="260">
        <template #default="scope">
          <!--小包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.upperQuantityMinActual" class="input-mr" clearable style="width: 80px;"
                      @blur="upperQuantityBlur(scope.row, scope.$index, 'min')"></el-input>
          </div>
          <!--大包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.upperQuantityMaxActual" class="input-mr" clearable style="width: 80px;"
                      @blur="upperQuantityBlur(scope.row, scope.$index, 'max')"></el-input>
          </div>
          <!--          <template v-else>-->
          <!--            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"-->
          <!--                           style="float: right"/>-->
          <!--            <div style="float: right;margin-right: 5px;font-weight: bold;">-->
          <!--              <el-input v-model="scope.row.upperQuantityMinActual" class="input-mr" clearable style="width: 80px;"-->
          <!--                        @blur="upperQuantityBlur(scope.row, scope.$index, 'min')"></el-input>-->
          <!--            </div>-->
          <!--          </template>-->
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="下限" prop="actualQuantity" width="260">
        <template #default="scope">
          <!--小包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.lowerQuantityMinActual" class="input-mr" clearable style="width: 80px;"
                      @blur="lowerQuantityBlur(scope.row, scope.$index, 'min')"></el-input>
          </div>
          <!--大包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.lowerQuantityMaxActual" class="input-mr" clearable style="width: 80px;"
                      @blur="lowerQuantityBlur(scope.row, scope.$index, 'max')"></el-input>
          </div>
          <!--          <template v-else>-->
          <!--            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"-->
          <!--                           style="float: right"/>-->
          <!--            <div style="float: right;margin-right: 5px;font-weight: bold;">-->
          <!--              <el-input v-model="scope.row.lowerQuantityMinActual" class="input-mr" clearable style="width: 80px;"-->
          <!--                        @blur="lowerQuantityBlur(scope.row, scope.$index, 'min')"></el-input>-->
          <!--            </div>-->
          <!--          </template>-->
        </template>
      </el-table-column>
      <el-table-column :align="'left'" fixed="right" label="操作" width="130">
        <template #default="scope">
          <el-tooltip class="item" content="保存" effect="dark" placement="left">
            <el-button circle type="primary" @click="handleSave(scope.row)">
              <svg-icon :icon-class="'save'"/>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="清除" effect="dark" placement="right">
            <el-button v-if="scope.row.drugStorageProfileId" circle type="danger" @click="handleDelete(scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :pageSizes="[pageSize, 1000]" :total="total" @pagination="paginationClick"/>
  </div>
</template>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {
  addDrugStorageProfile,
  delDrugStorageProfile,
  selectPageDrugStorageProfile
} from "@/api/drug/drugStorageProfile.ts";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no'))
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo

const {proxy} = getCurrentInstance() as any
const currentSelectDept = proxy.$currentSelectDept
// 总条数
const total = ref(0)
// 最终需要清空的id集合
const ids = ref<any>([])
const pageSize = ref<any>(30)
// 最后保存的list
const saveList = ref<any>([])
const drugStockList = ref<any>([])
// const queryParams = ref<any>({
//   pageNum: 1,
//   pageSize: 30,
//   storageId: currentSelectDept,
//   orgId: userInfo.orgId,
//   selectType: ""
// })
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 30,
  storageId: currentSelectDept,
  orgId: userInfo.orgId,
  drugName: undefined,
  drugInput: undefined,
  drugCode: undefined,
  selectType: "",
  itemInfo: undefined,
});

function storageIdClick(obj) {
  queryParams.value.storageId = obj.id
  getList();
}

function handleQuery() {
  getList();
}

function resetQuery() {

}


/** 查询药品库存列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  if (!proxy.$currentSelectDept) {
    return false
  }
  selectPageDrugStorageProfile(queryParams.value).then((response: any) => {
    drugStockList.value = response.rows;
    total.value = response.total;
    drugStockList.value.forEach((item: any) => {
      // 现有库存量
      item.quantityMax = Math.floor(item.quantity / item.packageNum)
      item.quantityMin = item.quantity % item.packageNum

      // 最上线转换的大包装数量
      item.upperQuantityMax = Math.floor(item.upperQuantity / item.packageNum)
      item.upperQuantityMin = item.upperQuantity % item.packageNum


      // 最下线转换的大包装数量
      item.lowerQuantityMax = Math.floor(item.lowerQuantity / item.packageNum)
      item.lowerQuantityMin = item.lowerQuantity % item.packageNum
      // 设置最上线和最小线数据
      if (item.lowerQuantity > 0) {
        // 数量/包装数量 的除数
        const bigNum = Math.floor(item.lowerQuantity / item.packageNum)
        // 数量/包装数量 的余数
        const minNum = item.lowerQuantity % item.packageNum
        item.lowerQuantityMaxActual = bigNum
        item.lowerQuantityMinActual = minNum
        // if (item.packageUnits === item.minUnits && minNum <= 0) {
        //   item.lowerQuantityMinActual = bigNum
        // }
      }
      if (item.upperQuantity > 0) {
        // 数量/包装数量 的除数
        const bigNum = Math.floor(item.upperQuantity / item.packageNum)
        // 数量/包装数量 的余数
        const minNum = item.upperQuantity % item.packageNum
        item.upperQuantityMaxActual = bigNum
        item.upperQuantityMinActual = minNum
        // if (item.packageUnits === item.minUnits && minNum <= 0) {
        //   item.upperQuantityMinActual = bigNum
        // }
      }
    })
  });
}

/**
 * 最上线输入框事件
 */
function upperQuantityBlur(row: any, index: number, type: string) {
  const packageNum = row.packageNum;
  const upperQuantityMinActual = row.upperQuantityMinActual || 0
  const upperQuantityMaxActual = row.upperQuantityMaxActual || 0
  // 必须是0和正整数验证
  if (!/^[0-9]\d*$/g.test(upperQuantityMaxActual)) {
    ElMessage.error("最大限制数不能为小数并且不能小于0");
  }
  if (!/^[0-9]\d*$/g.test(upperQuantityMinActual)) {
    ElMessage.error("最小限制数不能为小数并且不能小于0");
  }
  const rowIndex = Number(index) + 1
  if (type === "min") {
    if (packageNum > 1 && upperQuantityMinActual >= packageNum) {
      ElMessage.warning("药品第" + rowIndex + "行,最上线中小包装限制数量大于药品包装数量，系统自动转换为大包装数量")
      // 数量/包装数量 的除数
      const bigNum = Math.floor(upperQuantityMinActual / packageNum)
      // 数量/包装数量 的余数
      const minNum = upperQuantityMinActual % packageNum
      if (bigNum > 0) {
        // 将小包装数量置空，
        row.upperQuantityMinActual = 0
        // 大包装数量在原有的基础上加 整除的数
        row.upperQuantityMaxActual = Number(row.upperQuantityMaxActual || 0) + Number(bigNum)
        if (minNum != 0) {
          // 小包装数量在原有的基础上加 余数
          row.upperQuantityMinActual = Number(row.upperQuantityMinActual || 0) + Number(minNum)
        }
      }
    }
  }
}


/**
 * 最下线输入框事件
 */
function lowerQuantityBlur(row: any, index: number, type: string) {
  const packageNum = row.packageNum;
  const lowerQuantityMinActual = row.lowerQuantityMinActual || 0
  const lowerQuantityMaxActual = row.lowerQuantityMaxActual || 0
  // 必须是0和正整数验证
  if (!/^[0-9]\d*$/g.test(lowerQuantityMaxActual)) {
    ElMessage.error("最大限制数不能为小数并且不能小于0");
  }
  if (!/^[0-9]\d*$/g.test(lowerQuantityMinActual)) {
    ElMessage.error("最小限制数不能为小数并且不能小于0");
  }
  const rowIndex = Number(index) + 1
  if (type === "min") {
    if (packageNum > 1 && lowerQuantityMinActual >= packageNum) {
      ElMessage.warning("药品第" + rowIndex + "行,最下线中小包装限制数量大于药品包装数量，系统自动转换为大包装数量")
      // 数量/包装数量 的除数
      const bigNum = Math.floor(lowerQuantityMinActual / packageNum)
      // 数量/包装数量 的余数
      const minNum = lowerQuantityMinActual % packageNum
      if (bigNum > 0) {
        // 将小包装数量置空，
        row.lowerQuantityMinActual = 0
        // 大包装数量在原有的基础上加 整除的数
        row.lowerQuantityMaxActual = Number(row.lowerQuantityMaxActual || 0) + Number(bigNum)
        if (minNum != 0) {
          // 小包装数量在原有的基础上加 余数
          row.lowerQuantityMinActual = Number(row.lowerQuantityMinActual || 0) + Number(minNum)
        }
      }
    }
  }
}

/**
 * 单行保存
 */
function handleSave(row: any) {
  row.upperQuantity = computeCountNum(row.packageNum, row.upperQuantityMinActual, row.upperQuantityMaxActual);
  row.lowerQuantity = computeCountNum(row.packageNum, row.lowerQuantityMinActual, row.lowerQuantityMaxActual);
  saveList.value = []
  saveList.value.push(row)
  saveOk()
}

/**
 * 批量保存
 */
function saveBatch() {
  let filterList = drugStockList.value.filter((item: any) => {
    return item.upperQuantityMinActual != null || item.upperQuantityMaxActual != null
      || item.lowerQuantityMinActual != null || item.lowerQuantityMaxActual != null
  })
  saveList.value = []
  if (filterList.length > 0) {
    filterList.forEach((row: any) => {
      row.upperQuantity = computeCountNum(row.packageNum, row.upperQuantityMinActual, row.upperQuantityMaxActual);
      row.lowerQuantity = computeCountNum(row.packageNum, row.lowerQuantityMinActual, row.lowerQuantityMaxActual);
      saveList.value.push(row)
    })
    saveOk()
  }
}

/**
 * 保存提交
 */
function saveOk() {
  addDrugStorageProfile({"list": saveList.value}).then(() => {
    ElMessage.success("维护成功");
    getList();
  }).finally(() => {
  });
}

/** 单行清空 */
function handleDelete(row) {
  ids.value = []
  if (row.drugStorageProfileId) {
    ids.value.push(row.drugStorageProfileId)
    deleteOk()
  }
}

/** 批量清空 */
function deleteBatch() {
  ids.value = []
  const thisList = drugStockList.value.filter((item: any) => {
    return item.upperQuantityMinActual != null
  })
  ids.value = thisList.map((item: any) => item.drugStorageProfileId);
  if (ids.value.length > 0) {
    deleteOk()
  } else {
    ElMessage.error("没有需要清空的数据")
  }
}

function deleteOk() {
  const drugStorageProfileIds = ids.value;
  ElMessageBox.confirm('是否清空药品的库存限制？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugStorageProfile(drugStorageProfileIds).then(() => {
      getList();
      ElMessage.success("清除成功");
    })
  }).catch(() => {
  })
}

/**
 * 计算总数量
 * @param packageNum 包装数量
 * @param minQuantity 小包装数量
 * @param maxQuantity 大包装数量
 */
function computeCountNum(packageNum: number, minQuantity: number, maxQuantity: number) {
  debugger
  let saveAmount: number = Number(minQuantity || 0)
  if (packageNum != 1 && maxQuantity > 0) {
    saveAmount = Number((maxQuantity || 0) * packageNum) + Number(saveAmount)
  } else if (packageNum === 1 && minQuantity > 0) {
    saveAmount = Number((maxQuantity || 0) * packageNum) + Number(saveAmount)
  } else if (packageNum === 1 && minQuantity <= 0) {
    saveAmount = Number((maxQuantity || 0))
  }
  return saveAmount;
}

function paginationClick() {
  saveBatch()
  getList();

}

onBeforeUnmount(() => {
  saveBatch()
})


getList()
</script>

<script lang="ts">
export default {
  name: "DrugQuantityUpperAndLower"
}
</script>

<style scoped>
/* 列表点击行高亮 */
:deep(.el-table__body tr.current-row>td) {
  background-color: #e9e9e9 !important;
  color: #5f5f5f;
}

:deep(.input-mr .el-input__wrapper) {
  background-color: #ff000017;
}
</style>
